// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const db = uniCloud.database();
const { result } = require("xzs-utils");
// let dbJQL;

module.exports = {
	_before: function () { // 通用预处理器
		
		this.startTime = Date.now()
		
		let body = this.getHttpInfo().body
		if (!body) {
			throw result(400, "required")
		}
		this.params = JSON.parse(body)
		
		this.dbJQL = uniCloud.databaseForJQL({ // 获取JQL database引用，此处需要传入云对象的clientInfo
			clientInfo: this.getClientInfo()
		})
		this.dbJQL.setUser({
			uid: '6614cee821821b6d2bf33d83',
			role: ['admin']
		})
	},
	
	// 获取产品列表
	getList: async function() {
		let {navid, limit=5, size=0, keyword} = this.params
		if (!navid) {
			return result(400, "required")
		}
		
		// let res = await db.collection("xzs_product_list").where({
		// 	navid,
		// 	checked: true
		// }).skip(size).limit(limit).orderBy("orderid", "asc").get()
		// return result(0, "success", res.data)
		let wer
		if (keyword) {
			wer = {
				title: new RegExp(keyword, 'gi')
			}
		} else {
			wer = `navid == "${navid}" && checked == true`
		}
		let field = "picurl.url as picpath, title, grade, price, pronum, weight, year, orderid"
		// JQL语法使用
		let res = await this.dbJQL.collection("xzs_product_list").where(wer)
		.field(field).skip(size).limit(limit).orderBy("orderid", "asc").get()
		let count = await this.dbJQL.collection("xzs_product_list").where(wer).count()
		return result(0, "success", res.data, count.total)
	},
	
	// 获取产品详情
	detail: async function() {
		let {id} = this.params
		if (!id) return result(400, "required")
		let field = "picurl.url as picpath, title, grade, price, pronum, weight, year"
		// let res = await this.dbJQL.collection("xzs_product_list").doc(id).field(field).get()
		let res = await this.dbJQL.collection("xzs_product_list").where(`_id == "${id}"`)
		.field(field)
		.get({
			getOne: true
		})
		return result(0, "success", res.data)
	},
	
	_after: function(error, result) {
		if (error) {
			throw error
		}
		let timeCoast = Date.now() - this.startTime
		result.timeCoast = timeCoast
		return result
	}
}
